package com.log4jviewer.ui.preferences;

import org.eclipse.jface.preference.IPreferenceStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.log4jviewer.Activator;

/**
 * Class contains server settings. It loads and initializes them. It also provides default preferences.
 * 
 * @author <a href="mailto:rd.ryly@gmail.com">Ruslan Diachenko</a>
 */
public final class ServerPreferences {

    private static final String ID = "server";

    private static final String DEFAULT_PREFERENCES = initDefaultPreferences();

    private static final String SEPARATOR = ":";

    private static final String DEFAULT_HOST = "localhost";

    private static final int DEFAULT_PORT = 4445;

    private static final boolean DEFAULT_STARTED = false;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private String host;

    private int port;

    private boolean started;

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }

    public boolean isStarted() {
        return started;
    }

    public static String getId() {
        return ID;
    }

    public static String getDefaultPreferences() {
        return DEFAULT_PREFERENCES;
    }

    public static String getSeparator() {
        return SEPARATOR;
    }

    private static String initDefaultPreferences() {
        String defaulsPreferences = DEFAULT_HOST + SEPARATOR + String.valueOf(DEFAULT_PORT) + SEPARATOR
                + String.valueOf(DEFAULT_STARTED);
        return defaulsPreferences;
    }

    public void loadServerPreferences() {
        IPreferenceStore store = Activator.getInstance().getPreferenceStore();
        String prefs = store.getString(getId());
        String[] prefsList = prefs.split(SEPARATOR);

        final int hostIndex = 0;
        host = prefsList[hostIndex];
        logger.debug("Server host: {}", host);

        final int portIndex = 1;
        port = Integer.parseInt(prefsList[portIndex]);
        logger.debug("Server port: {}", port);

        final int startupIndex = 2;
        started = Boolean.parseBoolean(prefsList[startupIndex]);
        logger.debug("Server started: {}", started);
    }
}
